import jwt
from django.shortcuts import render

# Create your views here.
from django.utils.decorators import method_decorator
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo.settings import SECRET_KEY
from shopapp.sers import *


class CateView(APIView):
    def get(self, request):
        pid = request.GET.get("parent_id")
        queryset = Category.objects.filter(parent_id=pid)
        ser = CategorySer(queryset, many=True)
        return Response(ser.data)


class TagView(GenericAPIView, CreateModelMixin):
    serializer_class = TagSer

    def get(self, request):
        cate_id = request.GET.get("cate")
        if cate_id:
            queryset = Tag.objects.filter(cate=cate_id)
        else:
            queryset = Tag.objects.all()

        ser = TagSer(queryset, many=True)

        return Response(ser.data)

    def post(self, request):
        return self.create(request)

    def delete(self, request):
        pass

    def update(self, request):
        pass


class GoodsView(APIView):

    def get(self, request):
        queryset = Goods.objects.all()
        ser = GoodsSer(queryset, many=True)
        return Response(ser.data)

    def post(self, request):
        ser = GoodsSer(data=request.data)
        if ser.is_valid():
            goods = ser.save()

            # 获取标签id列表
            tag_ids = request.data.get("tag")

            print(tag_ids)
            goods_tag_list = []
            for tid in tag_ids:
                gt = Goods_Tag(tag_id=tid, goods_id=goods.id)
                goods_tag_list.append(gt)
            # 批量插入
            Goods_Tag.objects.bulk_create(goods_tag_list)

            return Response({"msg": "成功", "status": 200})
        else:
            print(ser.errors)
            return Response({"msg": "失败", "status": 500})


class GoodsInfoView(APIView):
    def get(self, request, id):
        goods = Goods.objects.get(id=id)
        ser = GoodsSer(goods)
        return Response(ser.data)


def check_token(func):
    def inner(request, *args):
        # 验证令牌
        token = request.GET.get("token")
        r = jwt.decode(token, SECRET_KEY, ["HS256"])
        request.uid = r["uid"]
        return func(request, *args)

    return inner


@method_decorator(check_token, name="dispatch")
class CartView(APIView):

    def get(self, request):

        # 根据用户的id 去查询 这个用户的所有购物车记录
        uid = request.uid
        queryset = Cart.objects.filter(user_id=uid)
        ser = CartListSer(queryset, many=True)

        return Response(ser.data)

    def post(self, request):
        # 向请求数据data中写入我们自己的字段
        request.data["user"] = request.uid

        # 判断该商品是否在购物车中,如果在购物车中 就追加个数
        queryset = Cart.objects.filter(user_id=r["uid"], goods_id=request.data.get("goods"))
        if queryset:
            # 如果 查找到了 证明 在数据库中存在 则去更新
            queryset.update(num=F("num") + request.data.get("num"))
            return Response({"msg": "添加成功", "status": 200})
        else:

            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"msg": "添加成功", "status": 200})
            else:
                print(ser.errors)
                return Response({"msg": "添加失败", "status": 500})


class CartInfoView(APIView):

    def delete(self, request, pk):
        Cart.objects.filter(id=pk).delete()

        return Response({"msg": "删除成功"})
